<template>
	<view class="c-sign" :style="{width,height}">
		<canvas class="canvas" :id="myCanvasId" type="2d"
		:canvas-id="myCanvasId" disable-scroll="true" @touchstart="ontouchstart" @touchmove="touchmove" @touchend="touchend"></canvas>
	</view>
</template>

<script>
	/**
	 * c-sign 电子签名
	 * @description 电子签名
	 * @property {String} canvasId 画布id
	 * @property {String} width 图像宽度 默认750rpx 单位rpx/px
	 * @property {String} height 图像高度 默认750rpx 单位rpx/px
	 * @property {Number} lineWidth 画笔宽度
	 * @property {String} lineColor 画笔颜色
	 * @property {String} bgColor 画布背景颜色
	 * @method {Function()} save 保存为图片
	 * @method {Function()} clear 清空画布
	 * */
	import uuid from './js/uuid.js'
	export default {
		name:"c-sign",
		props: {
			canvasId: {
				type: String,
				default:'myCanvas'
			},
			width: {
				type: String,
				default: '750rpx'
			},
			height: {
				type: String,
				default: '750rpx'
			},
			lineWidth:{ //画笔宽度
				type: Number,
				default: 4
			},
			lineColor:{
				type: String,
				default: '#000000'
			},
			bgColor:{
				type: String,
				default: '#ffffff'
			}
		},
		watch:{
			lineWidth(){
				this.ctx.lineWidth = this.lineWidth;
			},
			lineColor(){
				this.ctx.strokeStyle=this.lineColor
			},
			bgColor(){
				this.clear()
			}
		},
		data() {
			return {
				issave:false,//是否已保存
				points: [], //路径点集合 
			};
		},
		computed: {
			myCanvasId() {
				if (!this.canvasId) {
					return 'c' + uuid(18)
				} else {
					return this.canvasId
				}
			},
		},
		methods: {
			setBgColor(){
				// this.ctx.fillStyle = this.bgColor
				this.ctx.clearRect(0, 0, parseInt(this.width), parseInt(this.height));
				// #ifndef MP
				this.ctx.draw(true)
				// #endif
			},
			// #ifdef MP
				getContext(){
					return new Promise((resolve) => {
						const {pixelRatio} = uni.getSystemInfoSync()
						uni.createSelectorQuery()
							.in(this)
							.select(`#${this.canvasId}`)
							.fields({ node: true, size: true })
							.exec(res => {
								const {width,height}=res[0]
								const canvas = res[0].node
								canvas.width = res[0].width*pixelRatio
								canvas.height = res[0].height*pixelRatio
								resolve({canvas,width,height,pixelRatio})
							})
					})
				},
			// #endif
			async initCanvas() {
				// #ifdef MP
				const {canvas,pixelRatio}=await this.getContext()
				this.canvas = canvas
				this.ctx = canvas.getContext('2d')
				this.ctx.scale(pixelRatio,pixelRatio)
				// #endif
				
				// #ifndef MP
				this.ctx = uni.createCanvasContext(this.myCanvasId,this);
				// #endif
				
				//设置画笔样式
				this.ctx.lineWidth = this.lineWidth;
				this.ctx.lineCap = "round";
				this.ctx.lineJoin = "round";
				this.ctx.strokeStyle=this.lineColor
				
				this.setBgColor()
			},
			//触摸开始，获取到起点
			ontouchstart(e) {
				if(this.issave)return;
				const startX = e.changedTouches[0].x;
				const startY = e.changedTouches[0].y;
				let startPoint = {
					X: startX,
					Y: startY
				};
				this.points.push(startPoint);
				//每次触摸开始，开启新的路径
				this.ctx.beginPath();
			},
			//触摸移动，获取到路径点
			touchmove(e) {
				if(this.issave)return;
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					X: moveX,
					Y: moveY
				};
				this.points.push(movePoint); //存点
				let len = this.points.length;
				if (len >= 2) {
					this.draw(); //绘制路径
				}
		
			},
			// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
			touchend() {
				if(this.issave)return;
				this.points = [];
				this.isSign = true
			},
			/* ***********************************************
			#   绘制笔迹
			#   1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			#   2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			#   3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			************************************************ */
			draw() {
				let point1 = this.points[0]
				let point2 = this.points[1]
				this.points.shift()
				this.ctx.moveTo(point1.X, point1.Y)
				this.ctx.lineTo(point2.X, point2.Y)
				this.ctx.stroke()
				// #ifndef MP
				this.ctx.draw(true)
				// #endif
			},
			//清空画布
			clear() {
				this.setBgColor()
				// #ifndef MP
				this.ctx.draw(true);
				// #endif
				this.isSign = false
				// uni.getSystemInfo({
				// 	success:(res)=> {
				// 		let canvasw = res.windowWidth;
				// 		let canvash = res.windowHeight;
				// 		this.ctx.clearRect(0, 0,canvasw,canvash);
				// 		this.setBgColor()
				// 		// #ifndef MP
				// 		this.ctx.draw(true);
				// 		// #endif
				// 		this.isSign = false
				// 	},
				// })
			},
			dataURLtoBlob(dataURL) {
			  // 获取 Data URL 的数据部分，去掉头信息
			  let parts = dataURL.split(',');
			  let contentType = parts[0].split(':')[1];
			  let raw = parts[1];
			
			  // 将 Data URL 转换为 Blob 对象
			  let byteString = atob(raw);
			  let arrayBuffer = new ArrayBuffer(byteString.length);
			  let uint8Array = new Uint8Array(arrayBuffer);
			  for (let i = 0; i < byteString.length; i++) {
			    uint8Array[i] = byteString.charCodeAt(i);
			  }
			  return new Blob([arrayBuffer], {type: contentType});
			},
			save() {
				return new Promise((resolve,reject)=>{
					if(!this.isSign){
						reject({errCode:-1,errMsg:'请签名'})
						return
					}
					uni.canvasToTempFilePath({
						// #ifdef MP
						canvas: this.canvas,
						// #endif
						// #ifndef MP
						canvasId: this.myCanvasId,
						// #endif
						// fileType:'jpg',
						quality:1,
						success:async (res)=>{
							// console.log(res.tempFilePath)
							// #ifdef H5
							// let data = this.dataURLtoBlob(res.tempFilePath) // 不需要转化为本地地址 只需要base64
							// resolve({errMsg: "canvasToTempFilePath:ok",tempFilePath: res})
							resolve(res)
							// #endif
							// #ifdef APP-PLUS||MP
							resolve(res)
							// #endif
						},
						fail(err) {
							console.log(err);
							reject(err)
						}
					})
				})
				
			}
		},
		mounted() {
			this.$nextTick(()=>{
				this.initCanvas()
			})
		}
	}
</script>

<style lang="scss" scoped>
.c-sign{
	.canvas {
		width: 100%;
		height: 100%;
		// background-color: #ffffff;
	}
}
</style>
